<script setup>
import { ref } from "vue";
import { getPackageList, addPackage, delPackage, editPackage } from "@/utils/api/appPackage";
import { getFileList } from "@/utils/api/file";
import { dayjs, ElMessage } from "element-plus";
import { isEmptyObject, deepClone } from "@/utils/base";

// 列表数据
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(0);
const pageSize = ref(20);

const dataInit = async () => {
  loading.value = true;
  const res = await getPackageList({ pageNum: currentPage.value, pageSize: pageSize.value });
  if (res.success) {
    tableData.value = res.data.list;
    total.value = res.data.count;
  }
  loading.value = false;
};
dataInit();

const dialogFormVisible = ref(false);
const handleType = ref("");
const dialogForm = ref({});
// 添加
const handleAdd = () => {
  dialogFormVisible.value = true;
  handleType.value = "add";
  dialogForm.value = {};
};

// 编辑
const handleEdit = (row) => {
  dialogFormVisible.value = true;
  handleType.value = "edit";
  dialogForm.value = deepClone(row);
};

// 验证表单
const validateForm = (form) => {
  if (isEmptyObject(form)) {
    ElMessage.error("请填写表单");
    return false;
  }
  if (!form.app_name || !form.app_version || !form.app_size || !form.app_fileName || !form.app_description) {
    ElMessage.error("请填写完整信息");
    return false;
  }
  if (form.app_size) {
    form.app_size = Number(form.app_size);
  }
  return true;
};

// 提交表单
const submitForm = async (Form) => {
  if (!validateForm(Form)) {
    return;
  }
  try {
    if (handleType.value === "add") {
      const res = await addPackage(Form);
      if (res.success) {
        ElMessage.success("添加成功");
        dataInit();
      } else {
        ElMessage.error("添加失败");
      }
      resetForm();
    }
    if (handleType.value === "edit") {
      if (!Form.id) {
        ElMessage.error("请选择要编辑的应用包");
        return;
      }
      const res = await editPackage(Form);
      if (res.success) {
        ElMessage.success("编辑成功");
        dataInit();
      } else {
        ElMessage.error("编辑失败");
      }
      resetForm();
    }
  } catch (error) {
    console.log(error);
  }
};

// 重置
const resetForm = () => {
  dialogFormVisible.value = false;
  dialogForm.value = {};
  handleType.value = "";
};

// 删除
const handleDelete = async (row) => {
  try {
    const res = await delPackage({ ids: [row.id] });
    if (res.success) {
      ElMessage.success("删除成功");
      dataInit();
    } else {
      ElMessage.error("删除失败");
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取文件名选项
const systemFiles = ref([]);
const getSystemFiles = async () => {
  try {
    const res = await getFileList({ isPaging: 0, file_type: "other", use_type: "system" });
    if (res.success) {
      systemFiles.value = res.data.list;
    }
  } catch (error) {
    console.log(error);
  }
};
getSystemFiles();

const fileChange = (val) => {
  dialogForm.value.app_fileName = val.file_name;
  dialogForm.value.app_size = val.file_size;
};
</script>
<template>
  <div>
    <el-card class="box-card" shadow="never">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="handleAdd"
            ><el-icon> <Plus /> </el-icon> 添加应用包
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" stripe id="table-list" v-loading="loading" element-loading-text="Loading...">
        <el-table-column prop="app_name" label="应用名称" />
        <el-table-column prop="app_version" label="版本号" />
        <el-table-column prop="app_description" label="描述" />
        <el-table-column prop="app_size" label="大小" />
        <el-table-column prop="app_fileName" label="文件名" />
        <el-table-column label="创建时间">
          <template #default="scope">
            {{ dayjs(scope.row.create_time).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间">
          <template #default="scope">
            {{ dayjs(scope.row.update_time).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)" icon="Edit" circle />
            <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="danger" icon="Delete" circle />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="m-t">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 100, 200, 300, 400]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="dataInit"
          @current-change="dataInit"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="handleType === 'add' ? '添加应用包' : '编辑应用包'" width="30%">
      <el-form :model="dialogForm" label-width="auto">
        <el-form-item label="应用名称" required>
          <el-input v-model="dialogForm.app_name" clearable />
        </el-form-item>
        <el-form-item label="版本号" required>
          <el-input v-model="dialogForm.app_version" clearable />
        </el-form-item>
        <el-form-item label="文件名" required>
          <el-select v-model="dialogForm.app_fileName" filterable placeholder="请选择文件名" @change="fileChange">
            <el-option v-for="item in systemFiles" :key="item.id" :label="item.file_name" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="大小" required>
          <el-input type="number" v-model="dialogForm.app_size" clearable />
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input type="textarea" :rows="2" v-model="dialogForm.app_description" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(dialogForm)"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
